package com.zheng;


import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {
    private static ConcurrentHashMap<String, List<Long>> concurrentHashMap = new ConcurrentHashMap();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String method = invocation.getMethodName();
        long beginTime = System.currentTimeMillis();
        try {
            return invoker.invoke(invocation);
        } finally {
            long endTime = System.currentTimeMillis();
            long useTime = endTime - beginTime;
            if (concurrentHashMap.get(method) != null) {
                List<Long> list = concurrentHashMap.get(method);
                list.add(useTime);
                concurrentHashMap.put(method,list);
            } else {
                List<Long> list = new ArrayList<>();
                list.add(useTime);
                concurrentHashMap.put(method, list);
            }
            tpCount();
        }


    }
    public  synchronized void  tpCount() {

        for (Map.Entry<String, List<Long>> entry : concurrentHashMap.entrySet()) {
            String method = entry.getKey();
            List<Long> list = entry.getValue();
            //使用时间排序
            Collections.sort(list);
            int size = list.size();
            int tp99 = (int) Math.ceil(size * 0.99);
            int tp95 = (int) Math.ceil(size * 0.90);
            System.out.println("method:" + method + "-tp99:=" + list.get(tp99 - 1));
            System.out.println("method:" + method + "-tp90:=" + list.get(tp95 - 1));

        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
